package com.leyou.user.web;

import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.interceptors.LoginInterceptor;
import com.leyou.auth.utils.UserContext;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("info")
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 注册时校验检查用户输入信息的有效性
     * @param data
     * @param type
     * @return
     */
    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> checkExists(
            @PathVariable("data")String data,
            @PathVariable("type")Integer type){

        return ResponseEntity.ok(this.userService.checkExists(data,type));
    }

    /**
     * 发送短信验证码
     * @param phone
     * @return
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendVerifyCode(@RequestParam("phone")String phone){

        this.userService.sendVerifyCode(phone);
        return ResponseEntity.ok().build();
    }


    /**
     * 用户注册
     * @param user
     * @param code
     * Valid 表示开启校验支持
     * @return
     */
    @PostMapping
    public ResponseEntity<Void> register(
           @Valid User user,
            @RequestParam("code")String code){

        this.userService.register(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 用户的登录业务
     * @param username 用户名
     * @param password 密码
     * @return UserDTO 匹配到的具体的用户信息
     */
    @GetMapping
    public ResponseEntity<UserDTO> queryUserByNameAndPass(
            @RequestParam("username")String username,
            @RequestParam("password")String password){

        return ResponseEntity.ok(this.userService.queryUserByNameAndPass(username,password));
    }

    /**
     * 获取当前登录的用户信息
     * @return 用户信息
     */
    @GetMapping("me")
    public ResponseEntity<UserDetail> me(){
        //等业务执行时，拦截器已经执行完毕，用户信息存储在UserContext中，此时需要用户信息，只需要从userContext中获取
        return ResponseEntity.ok(UserContext.getUser());
    }

    //发送
    @GetMapping("/verificationCode")
    public  ResponseEntity<Void>  verificationCode(){
        this.userService.sendMessage();
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

}
